#!/usr/bin/env python3
"""
Prometheus Metrics Exporter
用于暴露系统指标给Prometheus监控
"""

from prometheus_client import start_http_server, Gauge, Counter, Histogram
import time
import random
# import threading
import psutil
import logging
from datetime import datetime

# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class SystemMetricsExporter:
    def __init__(self, port=8000):
        self.port = port

        # 定义指标
        self.cpu_usage = Gauge('system_cpu_usage_percent', 'CPU使用率百分比')
        self.memory_usage = Gauge('system_memory_usage_percent', '内存使用率百分比')
        self.disk_usage = Gauge('system_disk_usage_percent', '磁盘使用率百分比')
        self.request_count = Counter('http_requests_total', 'HTTP请求总数')
        self.request_duration = Histogram('http_request_duration_seconds', 'HTTP请求耗时')
        self.temperature = Gauge('system_temperature_celsius', '系统温度（模拟）')

        # 自定义业务指标
        self.active_users = Gauge('application_active_users', '活跃用户数')
        self.queue_size = Gauge('application_queue_size', '队列大小')

    def collect_system_metrics(self):
        """收集系统指标"""
        try:
            # CPU使用率
            cpu_percent = psutil.cpu_percent(interval=1)
            self.cpu_usage.set(cpu_percent)

            # 内存使用率
            memory = psutil.virtual_memory()
            self.memory_usage.set(memory.percent)

            # 磁盘使用率
            disk = psutil.disk_usage('/')
            self.disk_usage.set((disk.used / disk.total) * 100)

            # 模拟温度
            simulated_temp = 40 + random.uniform(-5, 5)
            self.temperature.set(simulated_temp)

        except Exception as e:
            logger.error(f"收集系统指标时出错: {e}")

    def collect_business_metrics(self):
        """收集业务指标"""
        try:
            # 模拟活跃用户数
            active_users = random.randint(100, 1000)
            self.active_users.set(active_users)

            # 模拟队列大小
            queue_size = random.randint(0, 500)
            self.queue_size.set(queue_size)

        except Exception as e:
            logger.error(f"收集业务指标时出错: {e}")

    def simulate_requests(self):
        """模拟HTTP请求"""
        try:
            # 增加请求计数
            self.request_count.inc()

            # 模拟请求处理时间
            with self.request_duration.time():
                processing_time = random.uniform(0.01, 2.0)
                time.sleep(processing_time)

        except Exception as e:
            logger.error(f"模拟请求时出错: {e}")

    def run_metrics_collection(self):
        """运行指标收集循环"""
        logger.info(f"启动指标收集器，端口: {self.port}")

        while True:
            try:
                self.collect_system_metrics()
                self.collect_business_metrics()

                # 随机模拟一些请求
                if random.random() < 0.3:  # 30%的概率模拟请求
                    self.simulate_requests()

                logger.debug("指标收集完成")
                time.sleep(10)  # 每10秒收集一次

            except Exception as e:
                logger.error(f"指标收集循环出错: {e}")
                time.sleep(30)

    def start(self):
        """启动exporter"""
        try:
            # 启动HTTP服务器
            start_http_server(self.port)
            logger.info(f"Prometheus exporter 启动在 http://0.0.0.0:{self.port}")

            # 启动指标收集
            self.run_metrics_collection()

        except Exception as e:
            logger.error(f"启动exporter失败: {e}")


def main():
    """主函数"""
    exporter = SystemMetricsExporter(port=8000)
    exporter.start()


if __name__ == "__main__":
    main()